# encoding: utf-8
import uuid
import time
import requests
import sys
import traceback
from apps.auth_util import gen_sign_headers

# 请替换APP_ID、APP_KEY
APP_ID = '2025336719'
APP_KEY = 'ZizATQhmSwylueBR'
URI = '/vivogpt/completions'
DOMAIN = 'api-ai.vivo.com.cn'
METHOD = 'POST'


def sync_vivogpt(prompt='你好，晓安！'):
    try:
        print(f"开始处理请求，prompt: {prompt}")
        params = {
            'requestId': str(uuid.uuid4())
        }
        print('requestId:', params['requestId'])

        data = {
            'prompt': prompt,
            'model': 'vivo-BlueLM-TB-Pro',
            'sessionId': str(uuid.uuid4()),
            'extra': {
                'temperature': 0.9
            }
        }
        print(f"请求数据: {data}")
        
        try:
            headers = gen_sign_headers(APP_ID, APP_KEY, METHOD, URI, params)
            print("生成签名头成功")
        except Exception as e:
            print(f"生成签名头失败: {str(e)}")
            traceback.print_exc()
            return None
            
        headers['Content-Type'] = 'application/json'
        print(f"请求头: {headers}")

        start_time = time.time()
        url = 'https://{}{}'.format(DOMAIN, URI)
        print(f"请求URL: {url}")
        
        try:
            # 增加超时设置
            response = requests.post(url, json=data, headers=headers, params=params, timeout=30)
            print(f"请求状态码: {response.status_code}")
        except requests.exceptions.Timeout:
            print("请求超时")
            return "非常抱歉，AI服务响应超时，请稍后再试。"
        except requests.exceptions.ConnectionError:
            print("连接错误")
            return "非常抱歉，连接AI服务失败，请检查网络连接。"
        except requests.exceptions.RequestException as e:
            print(f"请求异常: {str(e)}")
            traceback.print_exc()
            return "非常抱歉，调用AI服务出现问题，请稍后再试。"

        if response.status_code == 200:
            try:
                res_obj = response.json()
                print(f'response:{res_obj}')
                if res_obj['code'] == 0 and res_obj.get('data'):
                    content = res_obj['data']['content']
                    print(f'final content:\n{content}')
                    return content
                else:
                    print(f"API返回错误: code={res_obj.get('code')}, message={res_obj.get('message')}")
                    return "AI处理您的问题时遇到了一些困难，请换个问题试试。"
            except Exception as e:
                print(f"解析响应失败: {str(e)}")
                print(f"原始响应: {response.text}")
                traceback.print_exc()
                return "非常抱歉，处理AI响应时出现错误，请稍后再试。"
        else:
            print(f"请求失败: {response.status_code}")
            try:
                print(f"错误响应: {response.text}")
            except:
                print("无法获取错误响应内容")
            
            if response.status_code == 401 or response.status_code == 403:
                return "AI服务授权失败，请联系管理员检查API密钥配置。"
            elif response.status_code >= 500:
                return "AI服务器暂时不可用，请稍后再试。"
            else:
                return "调用AI服务失败，请稍后再试。"
        
        end_time = time.time()
        timecost = end_time - start_time
        print('请求耗时: %.2f秒' % timecost)
        return None
    except Exception as e:
        print(f"处理请求时发生未预期的错误: {str(e)}")
        traceback.print_exc()
        return "非常抱歉，系统处理您的请求时遇到了错误，请稍后再试。"


if __name__ == '__main__':
    if len(sys.argv) > 1:
        test_prompt = sys.argv[1]
    else:
        test_prompt = '你好，晓安！'
    result = sync_vivogpt(test_prompt)
    print(f"测试结果: {result}")